package com.qm.console.service.jw;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.qm.console.component.exception.BusinessException;
import com.qm.console.component.util.DateUtil;
import com.qm.console.component.util.HttpInvokeUtil;
import com.qm.console.controller.dto.ResultEnum;
import com.qm.console.dao.dm.SpiderArticleDOMapper;
import com.qm.console.model.SpiderArticleDO;
import com.qm.console.model.SpiderArticleDOExample;
import com.qm.console.model.SpiderArticleDOWithBLOBs;
import com.qm.console.pubdef.constant.UrlConstant;
import com.qm.console.pubdef.dto.jw.SpiderArticleQueryDTO;
import com.qm.console.pubdef.jw.dto.SpiderArticleDTO;
import com.qm.console.pubdef.jw.dto.UserTwitterDTO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * //                       _oo0oo_
 * //                      o8888888o
 * //                      88" . "88
 * //                      (| -_- |)
 * //                      0\  =  /0
 * //                    ___/`---'\___
 * //                  .' \\|     |// '.
 * //                 / \\|||  :  |||// \
 * //                / _||||| -:- |||||- \
 * //               |   | \\\  -  /// |   |
 * //               | \_|  ''\---/''  |_/ |
 * //               \  .-\__  '-'  ___/-. /
 * //             ___'. .'  /--.--\  `. .'___
 * //          ."" '<  `.___\_<|>_/___.' >' "".
 * //         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 * //         \  \ `_.   \_ __\ /__ _/   .-` /  /
 * //     =====`-.____`.___ \_____/___.-`___.-'=====
 * //                       `=---='
 * //
 * //
 * //     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * //
 * //               佛祖保佑         永无BUG
 * <p>
 * com.qm.console.service.jw
 * Created on 2021/8/23.
 */
@Component
public class JWContentService {

   @Autowired
   private DateUtil dateUtil;

   @Autowired
   private SpiderArticleDOMapper spiderArticleDOMapper;

   private static final String ROBOT_LIST_API =  UrlConstant.ApiServerHost+ "/user/robot";
   private static final String PUBLISH_CONTENT_API = UrlConstant.ApiServerHost + "/twitter";


   public List<SpiderArticleDTO> list(SpiderArticleQueryDTO queryDTO) {
      return spiderArticleDOMapper.list(queryDTO).stream().map(SpiderArticleDTO::fromDo).collect(Collectors.toList());
   }

   public int count(SpiderArticleQueryDTO queryDTO) {
       return spiderArticleDOMapper.count(queryDTO);
   }

   public int insertOrUpdate(SpiderArticleDTO update) {
      SpiderArticleDOWithBLOBs item = update.toDo();
      if (item.getId() == null) {
          item.setArticleId(UUID.randomUUID().toString());
          return spiderArticleDOMapper.insertSelective(item);
      } else {
          return spiderArticleDOMapper.updateByPrimaryKeySelective(item);
      }
   }

   public void delete(List<Integer> id) {
      SpiderArticleDOExample example = new SpiderArticleDOExample();
      List<Long> longIds = id.stream().map(Integer::longValue).collect(Collectors.toList());
      example.createCriteria().andIdIn(longIds);
      SpiderArticleDOWithBLOBs articleDO = new SpiderArticleDOWithBLOBs();
      articleDO.setDeleted((byte) 1);
      spiderArticleDOMapper.updateByExampleSelective(articleDO, example);
   }


   public JSONObject randomRobot() {
       String tempResult = HttpInvokeUtil.httpGet(ROBOT_LIST_API, ImmutableMap.of("limit", 1, "page",1));
       JSONObject tempJSONResult = JSONObject.parseObject(tempResult);
       if (tempJSONResult.getInteger("status") != 200) {
          throw new BusinessException(ResultEnum.FAILURE);
       }
       int total = tempJSONResult.getJSONObject("data").getInteger("total");
       int robotIndex = new Random().nextInt(total);

       String robotListString = HttpInvokeUtil.httpGet(ROBOT_LIST_API, ImmutableMap.of("limit", 1, "page", robotIndex + 1));

       JSONObject robotListResult = JSONObject.parseObject(robotListString);
       if (robotListResult.getInteger("status") != 200) {
          throw new BusinessException(ResultEnum.FAILURE);
       }
       JSONArray robotList = robotListResult.getJSONObject("data").getJSONArray("list");
       return robotList.getJSONObject(0);
   }

    public void addToRecommend(JSONArray ids) {
       List<Long> wrappedIds = ids.stream().map(i -> Long.valueOf(String.valueOf(i))).collect(Collectors.toList());
       SpiderArticleDOWithBLOBs spiderArticleDO = new SpiderArticleDOWithBLOBs();
       spiderArticleDO.setStatus(Constants.ARTICLE_STATUS_NEED_PUBLISH);
       SpiderArticleDOExample example = new SpiderArticleDOExample();
       example.createCriteria().andIdIn(wrappedIds);
       spiderArticleDOMapper.updateByExampleSelective(spiderArticleDO, example);
       pushToServer();
    }

    public void pushToServer() {
        // 然后在这里发布.
        SpiderArticleDOExample example = new SpiderArticleDOExample();
        example.createCriteria().andStatusEqualTo(Constants.ARTICLE_STATUS_NEED_PUBLISH);
        List<SpiderArticleDOWithBLOBs> articles = spiderArticleDOMapper.selectByExampleWithBLOBs(example);
        articles.forEach(this::pushToServerImpl);
    }

    private void pushToServerImpl(SpiderArticleDOWithBLOBs article) {
       if (article.getPublishTime().getTime() > System.currentTimeMillis()) {
           return;
       }
       UserTwitterDTO userTwitter = SpiderArticleDTO.fromDo(article).toUserTwitter();
       if (StringUtils.equals(userTwitter.getPictures(), "[]")) {
           userTwitter.setPictures("");
       }
       String resp = HttpInvokeUtil.httpPostJson(PUBLISH_CONTENT_API, JSONObject.parseObject(JSONObject.toJSONString(userTwitter)), "utf8", new HashMap<>(0));
       JSONObject respObj = JSONObject.parseObject(resp);
           SpiderArticleDOWithBLOBs updateStatus = new SpiderArticleDOWithBLOBs();
           updateStatus.setId(article.getId());
       if (respObj.getInteger("status") == 200) {
           updateStatus.setStatus(Constants.ARTICLE_STATUS_PUBLISHED);
           spiderArticleDOMapper.updateByPrimaryKeySelective(updateStatus);
       } else {
           updateStatus.setStatus(Constants.ARTICLE_STATUS_PUBLISH_FAILED);
       }
    }
}
